import 'dart:convert';
import 'dart:io';
import 'dart:math';
import 'dart:ui';

import 'package:dio/dio.dart';
import 'package:fate_blind_box/network/Api.dart';
import 'package:fate_blind_box/theme/theme_color.dart';
import 'package:fate_blind_box/utils/assets.dart';
import 'package:fate_blind_box/utils/bottom_sheet.dart';
import 'package:fate_blind_box/utils/common_widget.dart';
import 'package:fate_blind_box/utils/picker.dart';
import 'package:fate_blind_box/utils/provider.dart';
import 'package:fate_blind_box/utils/snack_bar.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:fate_blind_box/widget/date_picker/flutter_datetime_picker.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_picker/picker.dart';
import 'package:image_picker/image_picker.dart';
import 'package:universal_html/html.dart' as html;

import '../../utils/loading.dart';

class MemberDetail extends StatefulWidget {
   MemberDetail({Key? key}) : super(key: key);

  @override
  State<MemberDetail> createState() => _MemberDetailState();
}

class _MemberDetailState extends State<MemberDetail> {
  late double _screenWidth;
  final _user = <String, dynamic>{};
  final _mcs = <String, dynamic>{};
  final _desController = TextEditingController();
  late BuildContext _builderContext;
  final List<dynamic?> _avatarList = [];
  String? _albumId = "";
  final _nationList = [];
  final _pcaList = [];
  final _pcaOriginalList = [];
  String _sex = '';

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
      _initNations();
    _getMemberInfo();



  }

  /// 获取民族列表
  _initNations() async {
    final str = await loadAsset("nationality.json");
    List obj = json.decode(str);
    for (var element in obj) {
      _nationList.add(element);
    }
  }
  /// 根据id获取民族名称
  String _getNationById(id) {
    var s = "";
    for (var value in _nationList) {
      if (value['id'] == id) {
        s = value['name'];
        break;
      }
    }
    return s;
  }

  @override
  Widget build(BuildContext context) {
    _screenWidth = MediaQuery.of(context).size.width;
    return Scaffold(
      backgroundColor: Colors.white,
      body: Builder(
        builder: (ctx) {
          _builderContext = ctx;
          return Stack(
            children: [
              _user['profilePhoto']?.isNotEmpty == true ? Image.network(
                _user['profilePhoto'],
                width: _screenWidth,
                height: _screenWidth,
                fit: BoxFit.cover,
              ) : Container(
                color: Colors.white,
                width: _screenWidth,
                height: _screenWidth,
              ),
              BackdropFilter(
                filter: ImageFilter.blur(sigmaX: 6.0, sigmaY: 6.0),
                child: Opacity(
                  opacity: 0.5,
                  child: Container(
                    height: _screenWidth,
                    width: _screenWidth,
                    color: const Color.fromARGB(85, 0, 0, 0),
                  ),
                ),
              ),
              Column(
                children: [
                  AppWidget.statusBar(),
                  _buildTitleBar(),
                  Expanded(child: _buildContent()),
                ],
              )
            ],
          );
        },
      ),
    );
  }
  /// 标题栏
  Widget _buildTitleBar() {
    return Container(
        height: 56,
        width: _screenWidth,
        color: Colors.transparent,
        alignment: Alignment.centerLeft,
        child: GestureDetector(
          onTap: () { Navigator.of(context).pop();
          },
          child: const SizedBox(
            width: 56,
            height: 56,
            child: Icon(
              Icons.arrow_back_ios_new,
              color: Colors.white,
              size: 16,
            ),
          ),
        )
    );
  }
  /// 内容
  Widget _buildContent() {
    final list = [_buildAvatarProgress(),];

    final bgList = <Widget>[];
    bgList.addAll(_buildPersonalGallery());
    bgList.addAll(_buildPersonalDes());
    bgList.addAll(_buildBasicInfo());
    // bgList.addAll(_buildFamily());
    // bgList.addAll(_buildMarriagePlan());
    bgList.addAll(_buildSpouseRequirement());


    list.add(Container(
      margin: const EdgeInsets.only(top: 22),
      decoration: const ShapeDecoration(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.vertical(top: Radius.circular(15)),
          ),
          color: Colors.white
      ),
      child: Column(
        children: bgList,
      ),
    ));

    return SingleChildScrollView (
      physics: const BouncingScrollPhysics(),
      child: Column(
          children: list
      ),
    );
  }
  /// 头像和信息完成进度
  Widget _buildAvatarProgress() {
    return Stack(
      children: [
        Align(
          alignment: Alignment.topCenter,
          child: GestureDetector(
            onTap: () async {

            },
            child: ClipRRect(
              borderRadius: BorderRadius.circular(37),
              child: _user['profilePhoto']?.isNotEmpty == true ? Image.network(
                _user['profilePhoto'],
                width: 74,
                height: 74,
                fit: BoxFit.cover,
              ) : Image.asset(
                "images/ic_dma.png",
                width: 74,
                height: 74,
                fit: BoxFit.cover,
              ),
            ),
          ),
        ),
        Align(
          alignment: Alignment.topCenter,
          child: Container(
            margin: const EdgeInsets.only(top: 78),
            child: Text(
                "${_user["infoPer"]?? "0"}%",
                style: const TextStyle(
                  color: Colors.white,
                  fontSize: 18,
                )
            ),
          ),
        ),
        Container(
          alignment: Alignment.center,
          margin: const EdgeInsets.only(top: 100),
          child: const Text(
            "资料完整度越高，曝光率越高，社交能力越强哦",
            style: TextStyle(
                color: Colors.white,
                fontSize: 12
            ),
          ),
        )
      ],
    );
  }
  /// 信息标题
  Widget _buildInfoTitle(String percent, String title, String subTitle) {
    return Row(
      children: [
        Container(
          height: 56,
          width: _screenWidth,
          alignment: Alignment.center,
          padding: const EdgeInsets.symmetric(horizontal: 12),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text.rich(TextSpan(
                  children: [
                    TextSpan(
                        text: title,
                        style: TextStyle(
                            color: ThemeColor.textColor,
                            fontSize: 14,
                            fontWeight: FontWeight.bold
                        )
                    ),
                    subTitle == "" ? const TextSpan() : TextSpan(
                        text: subTitle,
                        style: TextStyle(
                            color: ThemeColor.textColorSecond,
                            fontSize: 12
                        )
                    )
                  ]
              )),
              Text(percent, style: TextStyle(color: ThemeColor.textColorSecond, fontSize: 12),),
            ],
          ),
        ),
      ],
    );
  }
  /// 个人照片
  List<Widget> _buildPersonalGallery() {
    return [
      _buildInfoTitle("+20%", "个人照片", "（${_avatarList.length}/9）"),
      Container(
        margin: const EdgeInsets.only(bottom: 22),
        height: 137,
        child: ListView.builder(
          scrollDirection: Axis.horizontal,
          itemCount: _avatarList.length < 9 ? _avatarList.length + 1 : 9,
          itemBuilder: (ctx, index) {
            dynamic img;
            if (index < _avatarList.length) {
              img = _avatarList[index];
            }
            return Container(
                width: 108,
                height: 137,
                margin: EdgeInsets.only(left: index == 0 ? 12 : 8, right: index == 8 ? 12 : 0),
                child: _avatarList.length < 9 && index == _avatarList.length ? GestureDetector(
                  onTap: () {


                  },
                  child: Container(
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                        border: Border.all(color: ThemeColor.dividerColor, width: 2),
                        borderRadius: BorderRadius.circular(4)
                    ),
                    child: Icon(
                      Icons.add_a_photo,
                      color: ThemeColor.textColorSecond,
                      size: 24,
                    ),
                  ),
                ) : ClipRRect(
                  borderRadius: BorderRadius.circular(4),
                  child: img is html.File ? Image.file(
                    img as File,
                    width: 108,
                    height: 137,
                    fit: BoxFit.cover,
                  ) : Image.network(
                    _avatarList[index],
                    width: 108,
                    height: 137,
                    fit: BoxFit.cover,
                  ),
                )
            );
          },
        ),
      ),
      const Text("完成真实头像认证，资料完整度越高", style: TextStyle(color: Color(0xFF45AEFE), fontSize: 12),)
    ];
  }
  /// 个人简介
  List<Widget> _buildPersonalDes() {
    return [
      _buildInfoTitle("10%", "个人简介", ""),
      Container(
        margin: const EdgeInsets.only(left: 20.0, top: 8.0, right: 20.0),
        padding: const EdgeInsets.all(12),
        decoration: ShapeDecoration(
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(4)
            ),
            color: const Color(0xFFF9F9F9)
        ),
        child: TextField(
          keyboardType: TextInputType.text,
          cursorColor: ThemeColor.mainColor,
          style: TextStyle(
            fontSize: 12,
            color: ThemeColor.textColor,
          ),
          maxLines: 5,
          controller: _desController,
          decoration: InputDecoration(

              hintText: "简单的介绍一下自己",
              isCollapsed: true,
              border: InputBorder.none,
              hintStyle: TextStyle(color: ThemeColor.textColorSecond),
              focusedBorder: const UnderlineInputBorder(
                  borderSide: BorderSide(color: Colors.transparent)
              ),
              enabledBorder: const UnderlineInputBorder(
                  borderSide: BorderSide(color: Colors.transparent)
              )
          ),
        ),
      ),
    ];
  }
  /// 信息item
  Widget _buildInfoItem(String key, dynamic value) {
    return Container(
      height: 52,
      margin: const EdgeInsets.symmetric(horizontal: 12),
      decoration: BoxDecoration(
        border: Border(
          bottom: BorderSide(
              width: 1,
              color: ThemeColor.dividerColor
          ),
        ),
      ),
      child: Row(
        children: [
          Text(key, style: TextStyle(color: ThemeColor.textColor, fontSize: 15),),
          Expanded(child: Text("$value", textAlign: TextAlign.right, style: TextStyle(color: ThemeColor.textColorSecond, fontSize: 15),)),
          const SizedBox(width: 8,),
          Icon(Icons.arrow_forward_ios, size: 14, color: ThemeColor.textColorSecond,)
        ],
      ),
    );
  }
  /// 基本资料
  List<Widget> _buildBasicInfo() {
    if (_user.isEmpty) {
      return List.empty();
    }
    return [
      _buildInfoTitle("+20%", "基本资料", ""),
      _buildInfoItem("性别", _sex),
      _buildInfoItem("民族",_getNationById(_user['nation']), ),
      _buildInfoItem("身高", "${_user['height']??""}cm",),
      _buildInfoItem("体重", "${_user['weight']??""}kg",),
      _buildInfoItem("出生日期", _user['bornDate']??"", ),
      // _buildInfoItem("属相", _user['animalSign']??"", "ZODIAC"),
      // _buildInfoItem("星座", _user['constellation']??"", "CONSTELLATION"),
      // _buildInfoItem("血型", _user['blood']?? "", "BLOOD"),
      _buildInfoItem("居住地", _user['homeAddr']??"", ),
      _buildInfoItem("户籍所在地", _user['domicilePlace']??"", ),
      _buildInfoItem("婚姻状况", _getMarital(_user['maritalStatus']), ),
      _buildInfoItem("有无小孩", _user['childNum'] == 0 ? "无" : "${_user['childNum']}个" , ),
      _buildInfoItem("学历", _getEdu(_user['edu']), ),
      _buildInfoItem("职业", _user['occipation']??"", ),
      _buildInfoItem("年收入", _getIncome(_user['incomeVal']), ),
      _buildInfoItem("有无住房", _user['purchase'] == 1 ? "有房" : "无房", ),
      _buildInfoItem("有无车", _user['buyCar'] == 1 ? "有车" : "无车", ),
      _buildInfoItem("是否抽烟喝酒", _user['aat'] == 1 ? "是" : "否", ),
      // _buildInfoItem("是否喝酒", _user['aat'] == 1 ? "是" : "否", "DRINK_WINE"),
    ];
  }

  String _getIncome(type) {
    List income = ['5万~10万', '10万~20万', '20万~50万', '50万~100万', '100万~300万', '300万以上'];
    if (type == null || type < 0 || type >= income.length) {
      return "--";
    }
    return income[type];
  }

  String _getEdu(type) {
    List edu = ['小学', '初中', '高中', '大专', '本科', '硕士', '博士', '教授'];
    if (type == null || type < 0 || type >= edu.length) {
      return '--';
    }
    return edu[type];
  }

  String _getMarital(status) {
    switch(status) {
      case 0:
        return "未婚";
      case 1:
        return "已婚";
      case 2:
        return "再婚";
      case 3:
        return "离异";
      case 4:
        return "丧偶";
      default: return "--";
    }
  }



  /// 择偶要求
  List<Widget> _buildSpouseRequirement() {
    return [
      _buildInfoTitle("+10%", "择偶要求", ""),
      _buildInfoItem("年龄", "${_mcs['ageStart']??18}~${_mcs['ageEnd']??50}", ),
      _buildInfoItem("身高", "${_mcs['heightStart']??150}~${_mcs['heightEnd']??200}", ),
      _buildInfoItem("体重", "${_mcs['weightStart']??40}kg~${_mcs['weightEnd']??100}kg", ),
      // _buildInfoItem("所在城市", "北京", "SPOUSE_LIVE"),
      _buildInfoItem("学历", _getEdu(_mcs['edu']??0),),
      _buildInfoItem("年收入", _getIncome(_mcs['incomeVal']??0), ),
      _buildInfoItem("购车", _mcs['buyCar'] == 1 ? "是" : "否", ),
      _buildInfoItem("购房", _mcs['purchase'] == 1 ? "是" : "否", ),
    ];
  }



  void _getMemberInfo() async {
    final res = await Api.getInstance().getMemberInfo(Provider.memberId);
    if (res['code'] == 0) {
      setState(() {
        _user.clear();
        print('---------------'+_user['nation'].toString());
        _user.addAll(res['data']);
        //0空 1男 2女
        if(_user['realSex'] == 0) {
          _sex = '';
        }else if(_user['realSex'] == 1) {
          _sex = '男';
        }else if(_user['realSex'] == 2) {
          _sex = '女';
        }
        if (_user['mcs'] != null) {
          _mcs.clear();
          _mcs.addAll(_user['mcs']);
        }
      });
      _desController.text = _user['signature']??"";
    } else {
      ThemeSnackBar.show(context, res['msg']);
    }
  }






}
